/*
 * @Author: Administrator
 * @Date:   2018-01-05 08:39:35
 * @Last Modified by:   Administrator
 * @Last Modified time: 2018-01-09 16:02:00
 */
import {
  observable,
  action,
  toJS,
} from 'mobx'
import getArcList from '../request/get_arc_list'
import { objToStrMap } from '../util/comm'
import { cancelRequest } from '../request/fetch'

// 技术文章
class PJ {
  constructor(initialState) {
    if (initialState && initialState.pj && initialState.pj.jokeList) {
      this.jokeList = objToStrMap(initialState.pj.jokeList)
    } else {
      this.jokeList = new Map()
    }
  }
  @observable jokeList
  @action getPj(cateId, pageSize, page = 1) {
    return new Promise((resolve, reject) => {
      const key = `list${cateId}${page}`
      if (this.jokeList.get(key)) {
        resolve()
        return
      }
      const params = {
        per_page: pageSize,
        categories: cateId,
        page,
      };
      // 请求数据
      getArcList(params).then((res) => {
        if (res.status === 200) {
          const data = []
          for (const article of res.data) {
            const {
              title,
              litpic,
              content,
              id,
            } = article
            const resArticle = {
              title,
              litpic,
              content,
              id,
            }
            data.push(resArticle)
          }
          this.jokeList.set(key, data)
          resolve()
        } else {
          reject(res.data)
        }
      }).catch(reject)
    })
  }
  toJson() {
    return {
      jokeList: toJS(this.jokeList),
    }
  }
  cancel() {
    cancelRequest();
  }
}
export default PJ
